package middleware

import (
	"context"
	"private-domain-overseas-service/pkg/result"
	"private-domain-overseas-service/pkg/xerr"

	"github.com/golang-jwt/jwt/v4"
	"net/http"

	"strings"
	"time"
)

type CheckAndFlushTokenMiddleware struct {
	Key string
}

func NewCheckAndFlushTokenMiddleware(key string) *CheckAndFlushTokenMiddleware {
	return &CheckAndFlushTokenMiddleware{
		Key: key,
	}
}

// Handle - JWT验签
func (m *CheckAndFlushTokenMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		authHeader := r.Header.Get("Authorization")
		if authHeader == "" {
			result.HttpResult(r, w, nil, xerr.ErrCodeMsg(xerr.ServerRequestParamError, "Authorization header required"))
			return
		}

		tokenString := strings.Replace(authHeader, "Bearer ", "", 1)
		token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
			if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
				return nil, jwt.ErrSignatureInvalid
			}
			return []byte(m.Key), nil
		})

		if err != nil {
			result.HttpResult(r, w, nil, xerr.ErrCodeMsg(xerr.ServerTokenInvalidError, "无效Token"))
			return
		}

		if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
			// 验证token是否过期
			if expiresAt, ok := claims["exp"].(float64); ok {
				if int64(expiresAt) < time.Now().Unix() {
					result.HttpResult(r, w, nil, xerr.ErrCodeMsg(xerr.ServerTokenExpireError, "Token过期"))
					return
				}
			}

			// 将用户信息添加到请求上下文中，方便后续使用
			ctx := context.WithValue(r.Context(), "bsu", claims["bsu"])
			r = r.WithContext(ctx)

			// 通过验证，继续处理请求
			next.ServeHTTP(w, r)
		} else {
			result.HttpResult(r, w, nil, xerr.ErrCodeMsg(xerr.ServerTokenInvalidError, "无效Token"))
			return
		}
	}
}
